package com.chuangke.security.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import cn.hutool.core.util.StrUtil;

/*
*   @Description  JwtUtil的工具类
*/
public class Jwtutil {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("token", "adadsfasfd");

		String SING = "aeqerqwer";
		String token = getToken(SING, map);

		System.out.println(token);

		DecodedJWT jwt = verify(SING, token);
		System.out.println(jwt);
	}

	public static String getToken(String secret, Map<String, String> claimMap) {
		return getToken(secret, null, claimMap);
	}

	/*
	 * 生成token 格式：header.payload.sing
	 */
	public static String getToken(String secret, Date expirationDate, Map<String, String> claimMap) {
		JWTCreator.Builder builder = JWT.create();
		// payload
		// 遍历存储payload信息
		claimMap.forEach(builder::withClaim);

		if (expirationDate != null) {
			builder.withExpiresAt(expirationDate);
		}

        return builder.sign(Algorithm.HMAC256(secret));
	}

	public static String getToken(HttpServletRequest request,String header) {
		String token = request.getHeader(header);
		String tokenHead = "Bearer ";
		if (token == null) {
			token = request.getHeader("token");
		} else if (token.contains(tokenHead)) {
			token = token.substring(tokenHead.length());
		}

		if (StrUtil.isBlank(token)) {
			token = request.getParameter("token");
		}

		if ("".equals(token)) {
			token = null;
		}
		return token;
	}

	/*
	 * 验证token合法性
	 */
	public static DecodedJWT verify(String secret, String token) {
		// 注意：验证时候一定要和生成时的 算法 和 签名SING 一致。
		return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
	}

	/*
	 * 获得token中的信息
	 */
	public static DecodedJWT getTokenInfo(String token) {
        return JWT.decode(token);
	}
}
